// server.js
const express = require('express');
const WebSocket = require('ws');
const bodyParser = require('body-parser');
var cors = require('cors')

const app = express();
const server = require('http').createServer(app);
app.use(cors())
const wss = new WebSocket.Server({ server });

app.use(bodyParser.json());

let rooms = {};

wss.on('connection', (ws, req) => {   //监听客户端连接 ws是新的WebSocket连接实例，req是与该连接相关的HTTP请求对象。
  const roomId = req.url.split('/')[2];  //获取客户端传来的房间号

  if (!rooms[roomId]) {   //如果该房间号不存在，则创建  用于存储该房间的所有WebSocket连接
    rooms[roomId] = [];
  }

  ws.on('message', (message) => {   //监听客户端发送的消息
    const data = JSON.parse(message);  //获取客户端发送的消息
    rooms[roomId].forEach((client) => {   //遍历该房间所有客户端，将消息发送给每个客户端，除了发送消息的客户端
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(data));
      }
    });
  });

  rooms[roomId].push(ws);  //将该客户端加入到该房间中

  ws.on('close', () => {    //监听客户端关闭连接事件
    rooms[roomId] = rooms[roomId].filter((client) => client !== ws);
  });
});

const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});